from typing import Annotated, Union
import jwt
from fastapi import Cookie, Header, HTTPException, Query, WebSocket, WebSocketException
from starlette import status

from api.internal import response
from api.router.model.user_model import User
from api.src.db.database import Session
from config import appSettings


async def get_token_header(x_token: str = Header(...)):
    if x_token != "Bearer":
        return HTTPException(status_code=401, detail="Invalid Token")


async def get_current_user(x_token: str = Header(...)):
    # jwt解密
    if not x_token.startswith("Bearer"):
        raise HTTPException(status_code=401, detail="Invalid Token#1")
    try:
        x_token_arr = x_token.split(" ")
        x_token = x_token_arr[1]
        if x_token is None:
            raise HTTPException(status_code=401, detail="Invalid Token empty#1")
        deploy = jwt.decode(
            x_token,
            appSettings.jwt_secret_key,
            algorithms=appSettings.jwt_algorithm,
            verify=True,
        )
        user = User(**deploy)
        print(user, deploy)
    except jwt.ExpiredSignatureError:
        raise HTTPException(status_code=401, detail="Signature has expired")
    except Exception as e:
        print(e)
        raise HTTPException(status_code=401, detail="Invalid Token")

    return user


async def get_query_token(token: str):
    if token != "Bearer":
        return HTTPException(status_code=401, detail="Invalid Token")


async def get_cookie_or_token(
    websocket: WebSocket,
    session: Annotated[Union[str, None], Cookie()] = None,
    x_token: str = Header(...),
):
    if session is None and x_token is None:
        raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)
    return await get_current_user(x_token)
